package spring.chatroom.java_chatroom.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import spring.chatroom.java_chatroom.mapper.ChatInfoMapper;
import spring.chatroom.java_chatroom.server.MesSendServer;
import spring.chatroom.java_chatroom.common.utils.SecurityUtil;
import spring.chatroom.java_chatroom.common.utils.SessionTracker;
import spring.chatroom.java_chatroom.common.utils.WebSocketSessionManagerUtil;
import spring.chatroom.java_chatroom.pojo.model.chatInfo;
import spring.chatroom.java_chatroom.pojo.model.sessionId;
import spring.chatroom.java_chatroom.pojo.response.response;
import spring.chatroom.java_chatroom.pojo.model.userInfo;
import spring.chatroom.java_chatroom.server.UserServer;

import java.io.IOException;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("chat")
public class UserController {

    @Autowired
    UserServer userServer;

    @Autowired
    MesSendServer sendServer;

    @Autowired
    ChatInfoMapper chatInfoMapper;

    //登录
    @RequestMapping("/login")
    public response login(String username, String password, HttpServletRequest request) {
        log.info("用户登录 ip={} | username={} | password={}", request.getRemoteAddr(), username, password);

        userInfo user = new userInfo(username, password);

        //验证用户是否存在
        userInfo userInfo = userServer.getUserInfoByName(username);

        if (!SecurityUtil.verify(password, userInfo.getPassword())) {
            return response.fail("密码错误");
        }

        //如果没有就创建一个新的会话
        HttpSession session = request.getSession(true);

        //判断下是否登录了
        HttpSession attribute = SessionTracker.getAttribute(userInfo.getUserId());
        //是这里把我的ai的session个删课
        if (attribute != null) {
            //那么就是登录了 移除上一个登录的session和websocket
            SessionTracker.removeAttribute(userInfo.getUserId());
            WebSocketSessionManagerUtil.removeAttribute(user.getUserId());
        }

        session.setAttribute("user", userInfo);

        SessionTracker.setAttribute(userInfo.getUserId(), session);

        //将密码给重置了
        userInfo.setPassword("");

        return response.success(userInfo);
    }

    //注册 用户名不能重复
    @RequestMapping("/register")
    public response register(String username, String password) {
        try {

            password = SecurityUtil.encrypt(password);

            userInfo userInfo = new userInfo(username, password);

            userInfo u = userServer.register(userInfo);

            u.setPassword("");

            initSomeBody(u);

            response success = response.success(u);

            return success;
        } catch (Exception e) {
            e.printStackTrace();
            return response.fail(e.getMessage());
        }
    }

    private void initSomeBody(userInfo u) {
        //给每个用户添加某人 userId = 0
        sessionId sessionId = userServer.addFriends(u.getUserId(), 0);

        chatInfo c = new chatInfo();
        c.setSessionId(sessionId.getId());
        c.setUserId(0);
        c.setContent("你好呀，我是r1:7b某人，我一直都在哦 ξ( ✿＞◡❛)");
        chatInfoMapper.insertInfo(c);

    }

    //这里转发加好友的信息 json
    @RequestMapping("tranFriendReq")
    public response tranFriendReq(@RequestBody @NotNull Map<String, Object> data) throws IOException {
        Integer userId = Integer.parseInt((String) data.get("userId"));
        Integer friendId = Integer.parseInt((String) data.get("friendId"));
        String content = (String) data.get("content");

        return response.success(userServer.tranFriendReq(userId, friendId,content));
    }

    //加好友by id 返回sessionId 如果是赏了之后在加回去那么就只是吧之前的sessionId对应的delete_flag置为0
    @RequestMapping("addFriends")
    public response addFriends(@RequestBody @NotNull Map<String, Integer> data) throws IOException {

        Integer userId = data.get("userId");
        Integer friendId = data.get("friendId");

        sessionId sessionId = userServer.addFriends(userId, friendId);
        //告诉对方
        sendServer.addFriendAgree(friendId);

        return response.success(sessionId);
    }

    //删除好友
    @RequestMapping("delFriend")
    public response delFriend(@RequestBody @NotNull Map<String, Integer> data) throws IOException {

        Integer sessionId = data.get("delId");

        userServer.delFriend(sessionId);

        return response.success("");
    }

    //删除消息
    @RequestMapping("delMsg")
    public response delMsg(@RequestBody Map<String, Integer> data) {
        Integer delId = data.get("delId");
        return response.success(userServer.delMsg(delId));
    }

    //获得用户的信息
    @RequestMapping("/userInfo")
    public response userInfo(@NotNull Integer userId) {

        /**
         * todo 根据id来获得用户的信息，并返回
         * 格式 userId userName
         */
        return response.success(userServer.getUserInfo(userId));
    }

    //获得朋友的聊天信息
    @RequestMapping("/friendList")
    public response friendList(@NotNull Integer userId) {
        /**
         * todo 根据用户的id来获得他的朋友信息
         * 格式 sessionId friendId friendName
         */
        return response.success(userServer.getFriendList(userId));
    }

    //获得朋友的聊天信息
    @RequestMapping("/friendSessionList")
    public response friendSessionList(@NotNull Integer userId) {
        /**
         * todo 根据用户的id来获得他的朋友信息 还要返回最近的消息
         * 格式 friendId friendName content
         */
        return response.success(userServer.getFriendSessionList(userId));
    }

    //获得的是聊天框的最近的聊天记录 左边的框
    @RequestMapping("getHistoryMessage")
    public response getHistoryMessage(@NotNull Integer sessionId) {
        /**
         * todo 按降序排序 返回
         */
        return response.success(userServer.sessionList(sessionId));
    }
}
